//
//  ViewController.swift
//  Example
//
//  Created by QDSG on 2021/7/23.
//

import UIKit
import RxSwift
import RxCocoa

struct DataModel {
    let className: UIViewController.Type?
    let name: String?
}

struct DataModelList {
    let data = Observable.just([
        DataModel(className: ObservableViewController.self, name: "Observable创建与订阅"),
        DataModel(className: SubjectsViewController.self, name: "Subjects"),
        DataModel(className: CombineObservablesViewController.self, name: "结合操作符"),
        DataModel(className: TransformObservableViewController.self, name: "映射操作符"),
        DataModel(className: FilterObservableViewController.self, name: "过滤操作符"),
        DataModel(className: SetControlObservableViewController.self, name: "集合控制操作符"),
        DataModel(className: ErrorHandleObservableViewController.self, name: "错误处理"),
        DataModel(className: DebugViewController.self, name: "调试操作"),
        DataModel(className: ConnectableObservableViewController.self, name: "连接操作符"),
        DataModel(className: OtherObservableViewController.self, name: "其它操作符"),
        DataModel(className: TraitsViewController.self, name: "特征序列1：Single、Completable、Maybe等"),
        DataModel(className: DriverViewController.self, name: "特征序列2：Driver"),
        DataModel(className: ControlSequenceViewController.self, name: "特征序列3：ControlProperty、 ControlEvent"),
        DataModel(className: RxExampleViewController.self, name: "给 UIViewController 添加 RxSwift 扩展"),
        DataModel(className: SchedulersViewController.self, name: "调度器 Schedulers"),
        DataModel(className: UILabelViewController.self, name: "UILabel+Rx扩展"),
        DataModel(className: UITextFieldViewController.self, name: "UITextField+Rx扩展"),
        DataModel(className: UITextViewViewController.self, name: "UITextView+Rx扩展"),
        DataModel(className: UIButtonViewController.self, name: "UIButton+Rx扩展"),
        DataModel(className: UISwitchViewController.self, name: "UISwitch+Rx扩展"),
        DataModel(className: UISegmentedControlViewController.self, name: "UISegmentedControl+Rx扩展"),
        DataModel(className: UIActivityIndicatorViewViewController.self, name: "UIActivityIndicatorView+Rx扩展"),
        DataModel(className: UIApplicationViewController.self, name: "UIApplication+Rx扩展"),
        DataModel(className: UISliderViewController.self, name: "UISlider+Rx扩展"),
        DataModel(className: UIStepperViewController.self, name: "UIStepper+Rx扩展"),
        DataModel(className: UIGestureRecognizerViewController.self, name: "UIGestureRecognizer+Rx扩展"),
        DataModel(className: UIDatePickerViewController.self, name: "UIDatePicker+Rx扩展"),
    ])
}

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    private var disposeBag = DisposeBag()
    
    private let dataList = DataModelList()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        
//        rxswiftTest()
    }

    private func rxswiftTest() {
        // 1、创建序列
        _ = Observable<String>.create({ observer in
            // 3、发送信号
            observer.onNext("11111111111")
            return Disposables.create()
        })
        // 2、订阅序列
        .subscribe(onNext: { text in
            print("订阅到：\(text)")
        })
    }
    
    private func makeUI() {
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
        dataList.data
            .bind(to: tableView.rx.items(cellIdentifier: "cell")) { _, model, cell in
                cell.textLabel?.text = model.name
            }.disposed(by: disposeBag)
        
        tableView.rx
            .modelSelected(DataModel.self)
            .subscribe { event in
                if let vcClass = event.element?.className {
                    let vc = vcClass.init()
                    vc.title = event.element?.name
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }.disposed(by: disposeBag)
    }
}

// MARK: - 高阶函数

@discardableResult
func delay(_ interval: TimeInterval, qosClass: DispatchQoS.QoSClass? = nil, closure: (() -> Void)? = nil) -> ((Bool) -> Void)? {
    func dispatch_later(closure: @escaping () -> Void) {
        let queue = qosClass != nil ? DispatchQueue.global(qos: qosClass!) : .main
        queue.asyncAfter(deadline: .now() + interval, execute: closure)
    }
    
    var block = closure
    var result: ((Bool) -> Void)?
    
    let delayedClosure: (Bool) -> Void = { cancel in
        if let intervalClosure = block {
            if !cancel {
                DispatchQueue.main.async(execute: intervalClosure)
            }
        }
        
        block = nil
        result = nil
    }
    
    result = delayedClosure
    
    dispatch_later {
        if let delayedClosure = result {
            delayedClosure(false)
        }
    }
    
    return result
}

/// 取消代码延时运行
func delayCancel(closure: ((Bool) -> Void)?) {
    closure?(true)
}
